/*
 * Title:        CloudScheduler Toolkit
 * Description:  a Toolkit for Modeling and Simulation of Job Scheduling and Resource Provisioning in Cloud System
 * Licence:      GPL - http://www.gnu.org/copyleft/gpl.html
 * Author:       Fuhui Wu
 *
 * Copyright (c) 2013-2014, The National University of Defense Technology, China
 */

package org.nudt.jCloud.fileSystem;

import java.util.Random;

import org.nudt.jCloud.infrastructure.Cluster;

public class BalanceStorer implements Storer{

	@Override
	public boolean store(File file, Cluster cluster) {
		Random r = new Random(file.getId()+System.currentTimeMillis());
		int numHost = cluster.getHostList().size();
		int index = -1;
		for(int i=0; i<file.getBlockList().size(); ++i){
			boolean stored = false;
			index = r.nextInt(numHost);
			for(int j=index; j<numHost; ++j){
				if(cluster.getHostList().get(j).getAvailableStorage()>=file.getBlockList().get(i).getLength()){
					cluster.getHostList().get(j).getStorageProvisioner().occupy(file.getBlockList().get(i).getLength());
					file.getBlockList().get(i).store(cluster.getHostList().get(j));
					stored = true;
					break;
				}
			}
			if(stored == false){
				for(int j=0; j<index; ++j){
					if(cluster.getHostList().get(j).getAvailableStorage()>=file.getBlockList().get(i).getLength()){
						cluster.getHostList().get(j).getStorageProvisioner().occupy(file.getBlockList().get(i).getLength());
						file.getBlockList().get(i).store(cluster.getHostList().get(j));
						stored = true;
						break;
					}
				}
			}
			if(stored ==false){
				throw new RuntimeException("Cannot store this file.");
			}
		}
		return false;
	}

}
